package metu.tespit.session.projectteam;

import java.util.List;

import javax.persistence.EntityManager;

import metu.tespit.entitiy.accountManagement.User;
import metu.tespit.entity.course.ProjectTeam;
import metu.tespit.session.EntityManager.ExtendedEntityHome;
import metu.tespit.session.course.CourseHome;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Transactional;

/**
 
 * @created May 29, 2012
 */
@Name("projectTeamHome")
public class ProjectTeamHome extends ExtendedEntityHome<ProjectTeam>{
	/**
	 * 
	 */
	private static final long serialVersionUID = -76541864982342l;
	
	@In(create=true)
	CourseHome courseHome;

    @Transactional
	public String persistWithCourse(){
	
		if(courseHome!=null){
			
			this.instance.setCourse(courseHome.getInstance());
			//courseHome.getInstance().getProjectTeams().add(this.instance);
			for(User u : this.instance.getStudents()){
				u.setProjectTeam(this.instance);
			}
			return super.persist();
		}else{
			
			return "FAIL";
		}
		
	}
    
    @In
    EntityManager entityManager;
    
    @Transactional
	public String updateWithCourse(){
	
    	
    	List<User> userList =(List<User>)entityManager.createQuery("Select u from User u where u.projectTeam.id=:id").setParameter("id", this.instance.getId()).getResultList();
    	
		if(courseHome!=null){
			
			this.instance.setCourse(courseHome.getInstance());
			//courseHome.getInstance().getProjectTeams().add(this.instance);
			for(User u : this.instance.getStudents()){
				u.setProjectTeam(this.instance);
				userList.remove(u);
			}
			for(User u : userList){
				u.setProjectTeam(null);
			}
			return super.update();
		}else{
			
			return "FAIL";
		}
		
	}

	public void setTeamId(Long teamId) {
		setId(teamId);
	}

	public Long getTeamId() {
		return (Long) getId();
	}
	
}
